// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/dwio/dwrf/reader/selective_dwrf_reader.h>
#include <pollux/dwio/common/type_utils.h>

#include <pollux/dwio/dwrf/reader/selective_byte_rle_column_reader.h>
#include <pollux/dwio/dwrf/reader/selective_decimal_column_reader.h>
#include <pollux/dwio/dwrf/reader/selective_flat_map_column_reader.h>
#include <pollux/dwio/dwrf/reader/selective_floating_point_column_reader.h>
#include <pollux/dwio/dwrf/reader/selective_integer_dictionary_column_reader.h>
#include <pollux/dwio/dwrf/reader/selective_integer_direct_column_reader.h>
#include <pollux/dwio/dwrf/reader/selective_repeated_column_reader.h>
#include <pollux/dwio/dwrf/reader/selective_string_dictionary_column_reader.h>
#include <pollux/dwio/dwrf/reader/selective_string_direct_column_reader.h>
#include <pollux/dwio/dwrf/reader/selective_struct_column_reader.h>
#include <pollux/dwio/dwrf/reader/selective_timestamp_column_reader.h>

namespace kumo::pollux::dwrf {

using namespace kumo::pollux::dwio::common;

std::unique_ptr<SelectiveColumnReader> buildIntegerReader(
    const TypePtr& requestedType,
    const std::shared_ptr<const dwio::common::TypeWithId>& fileType,
    DwrfParams& params,
    uint32_t numBytes,
    common::ScanSpec& scanSpec) {
  const EncodingKey encodingKey{
      fileType->id(), params.flatMapContext().sequence};
  auto& stripe = params.stripeStreams();

  if (StripeStreamsUtil::isColumnEncodingKindDictionary(stripe, encodingKey)) {
    return std::make_unique<SelectiveIntegerDictionaryColumnReader>(
        requestedType, fileType, params, scanSpec, numBytes);
  } else if (StripeStreamsUtil::isColumnEncodingKindDirect(
                 stripe, encodingKey)) {
    return std::make_unique<SelectiveIntegerDirectColumnReader>(
        requestedType, fileType, params, numBytes, scanSpec);
  } else {
    const auto encodingKind = stripe.format() == DwrfFormat::kDwrf
        ? static_cast<int64_t>(stripe.getEncoding(encodingKey).kind())
        : static_cast<int64_t>(stripe.getEncodingOrc(encodingKey).kind());
    POLLUX_FAIL("buildReader unhandled integer encoding: {}", encodingKind);
  }
}

// static
std::unique_ptr<SelectiveColumnReader> SelectiveDwrfReader::build(
    const TypePtr& requestedType,
    const std::shared_ptr<const dwio::common::TypeWithId>& fileType,
    DwrfParams& params,
    common::ScanSpec& scanSpec,
    bool isRoot) {
  POLLUX_CHECK(
      !isRoot || fileType->type()->kind() == TypeKind::ROW,
      "The root object can only be a row.");

  dwio::common::typeutils::checkTypeCompatibility(
      *fileType->type(), *requestedType);
  EncodingKey ek{fileType->id(), params.flatMapContext().sequence};
  auto& stripe = params.stripeStreams();
  switch (fileType->type()->kind()) {
    case TypeKind::INTEGER:
      return buildIntegerReader(
          requestedType, fileType, params, INT_BYTE_SIZE, scanSpec);
    case TypeKind::BIGINT:
      if (fileType->type()->isDecimal()) {
        return std::make_unique<SelectiveDecimalColumnReader<int64_t>>(
            fileType, params, scanSpec);
      } else {
        return buildIntegerReader(
            requestedType, fileType, params, LONG_BYTE_SIZE, scanSpec);
      }
    case TypeKind::SMALLINT:
      return buildIntegerReader(
          requestedType, fileType, params, SHORT_BYTE_SIZE, scanSpec);
    case TypeKind::ARRAY:
      return std::make_unique<SelectiveListColumnReader>(
          requestedType, fileType, params, scanSpec);
    case TypeKind::MAP:
      if (stripe.format() == DwrfFormat::kDwrf &&
          stripe.getEncoding(ek).kind() ==
              proto::ColumnEncoding_Kind_MAP_FLAT) {
        return createSelectiveFlatMapColumnReader(
            requestedType, fileType, params, scanSpec);
      }
      return std::make_unique<SelectiveMapColumnReader>(
          requestedType, fileType, params, scanSpec);
    case TypeKind::REAL:
      if (requestedType->kind() == TypeKind::REAL) {
        return std::make_unique<
            SelectiveFloatingPointColumnReader<float, float>>(
            requestedType, fileType, params, scanSpec);
      } else {
        return std::make_unique<
            SelectiveFloatingPointColumnReader<float, double>>(
            requestedType, fileType, params, scanSpec);
      }
    case TypeKind::DOUBLE:
      return std::make_unique<
          SelectiveFloatingPointColumnReader<double, double>>(
          requestedType, fileType, params, scanSpec);
    case TypeKind::ROW:
      return std::make_unique<SelectiveStructColumnReader>(
          requestedType, fileType, params, scanSpec, isRoot);
    case TypeKind::BOOLEAN:
      return std::make_unique<SelectiveByteRleColumnReader>(
          requestedType, fileType, params, scanSpec, true);
    case TypeKind::TINYINT:
      return std::make_unique<SelectiveByteRleColumnReader>(
          requestedType, fileType, params, scanSpec, false);
    case TypeKind::VARBINARY:
    case TypeKind::VARCHAR:
      if (StripeStreamsUtil::isColumnEncodingKindDictionary(stripe, ek)) {
        return std::make_unique<SelectiveStringDictionaryColumnReader>(
            fileType, params, scanSpec);
      } else if (StripeStreamsUtil::isColumnEncodingKindDirect(stripe, ek)) {
        return std::make_unique<SelectiveStringDirectColumnReader>(
            fileType, params, scanSpec);
      } else {
        DWIO_RAISE("buildReader string unknown encoding");
      }
    case TypeKind::TIMESTAMP:
      return std::make_unique<SelectiveTimestampColumnReader>(
          fileType, params, scanSpec);
    case TypeKind::HUGEINT:
      if (fileType->type()->isDecimal()) {
        return std::make_unique<SelectiveDecimalColumnReader<int128_t>>(
            fileType, params, scanSpec);
      }
      [[fallthrough]];
    default:
      POLLUX_FAIL(
          "buildReader unhandled type: " +
          mapTypeKindToName(fileType->type()->kind()));
  }
}

} // namespace kumo::pollux::dwrf
